package com.lechi.web.util;

import com.lechi.web.common.utils.DateUtils;
import com.lechi.web.constants.Constants;
import com.lechi.web.framework.util.GuavaCacheUtil;
import com.lechi.web.system.domain.IotMonitorDataBo;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;

/**
 * 指令监听器
 */
@Slf4j
public class RecordFileUtil {

    public static void producerRecord(String protocolType, List<IotMonitorDataBo> deviceDataList) {
        CompletableFuture.runAsync(() -> {
            if (deviceDataList.isEmpty()) {
                return;
            }
            IotMonitorDataBo iotMonitorDataBo = deviceDataList.get(0);
            String fileName = GuavaCacheUtil.getDeviceTableMap().get(Constants.WRITE_RECORD_LOG_NAME, String.valueOf(iotMonitorDataBo.getDeviceId()));
            if (Objects.nonNull(fileName)) {
                try {
                    Files.createDirectories(Paths.get(fileName.substring(0, fileName.lastIndexOf("/"))));
                    StandardOpenOption[] options = {StandardOpenOption.CREATE, StandardOpenOption.APPEND};
                    Files.write(Paths.get(fileName), ("receiveTime:" + DateUtils.getTime() + ", data:" + iotMonitorDataBo.getReceiveData() + "\n").getBytes(), options);
                } catch (IOException e) {
                    log.error("写入传感器数据产生异常!", e);
                }
            }
        });
    }

}
